<!--
 * @description  : 案件详情信息-窝点信息
 * @descriptionDetail: 案件详情信息-窝点信息
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-09 18:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->
    <view class="content">
      <view class="party-info-content">
        <view class="party-info-box">
          <view style="width: calc(100% + 30px);">
            <form-section title="基本信息"></form-section>
          </view>
          <u-form :model="dataForm" label-position="top" :rules="rules" :errorType="errorType" ref="uForm">
            <u-form-item label="窝点名称" :required="isTrue" prop="densName">
              <!-- <u-input placeholder="请输入名称" :disabled="isDisabled" v-model="dataForm.densName" /> -->
              <auto-input
                absIndex="1"
                :searchData="shipInfo"
                absClass="caseAviaClass"
                :disabled="isDisabled"
                placeholder="请输入窝点名称"
                v-model="dataForm.densName"
                @choiceAutoItem="choiceAutoItem"
              >
              </auto-input>
            </u-form-item>
            <u-form-item label="窝点类型" :required="isTrue" prop="densType">
              <dic-input
                :keyWord="$u.dic.DIC_KEYS.C_DENS_TYPE"
                :dicCode="dataForm.densType"
                type="text"
                :border="border"
                :disabled="true"
								:custom-style="pointerStyle"
                :select-open="dicSelectOpen($u.dic.DIC_KEYS.C_DENS_TYPE)"
                placeholder="请选择窝点类型"
                v-model="dataForm.densTypeName"
                @changeInputModelData="
                  (name) => {
                    $set(dataForm, 'densTypeName', name);
                  }
                "
                @click="showDic($u.dic.DIC_KEYS.C_DENS_TYPE, dataForm.densType)"
              />
            </u-form-item>

            <u-form-item label="窝点小类" :required="isTrue" prop="densSubType">
              <u-input :border="border" type="select" :select-open="subTypeShow" placeholder="请选择" v-model="dataForm.densSubTypeName" @click="openSubType()"></u-input>
              <u-select mode="single-column" label-name="text" :list="subTypeList" v-model="subTypeShow" @confirm="selectConfirm($event,'densSubType')"></u-select>
            </u-form-item>

            <u-form-item label="登记单位" :required="true" prop="remoteOrgName" right-icon="arrow-right">
              <u-input
                :disabled="true"
                placeholder="请选择"
								:custom-style="pointerStyle"
                v-model="dataForm.remoteOrgName"
                @click="openOrgSelectShow"
              >
              </u-input>
            </u-form-item>

            <u-form-item label="所在地" prop="denProvCityCounty" :required="true">
              <view style="display: flex; flex-direction: column;width: 100%;">
                <u-input
                  type="select"
                  :disabled="true"
									:custom-style="pointerStyle"
                  placeholder="所在地选择"
                  v-model="dataForm.denProvCityCounty"
                  @click="openNativeNameSelectShow"
                ></u-input>
                <u-line :color="$theme.u_border_color" style="margin: 10rpx 0;"></u-line>
                <u-row gutter="16">
                  <u-col span="12">
                    <u-input :border="true" :disabled="isDisabled" placeholder="输入窝点地址" v-model="dataForm.densAddr"></u-input>
                  </u-col>
                </u-row>
              </view>
            </u-form-item>
            <u-form-item label="窝点gis经纬度">
              <u-input placeholder="请选择" v-model="dataForm.gis" :disabled="true"></u-input>
              <u-icon name="map-fill" :color="$theme.u_type_primary" size="44" @click="setLocation()"></u-icon>
            </u-form-item>
            <u-form-item label="备注">
              <u-input type="textarea" height="100" :auto-height="true" placeholder="请输入" :disabled="isDisabled" v-model="dataForm.remark" />
            </u-form-item>
            <u-form-item label="图片信息">
              <view class="zk-img-content">
                <m-upload
                  :deletable="true"
                  :maxCount="picIds"
                  width="150rpx"
                  height="150rpx"
                  :file-list="fileList"
                  :multiple="true"
                  :disabled="isDisabled"
                  index="fileList"
                  :uploadParam="{'fiGroupCode':$FILE_GROUP_TYPE.c_case_dens}"
                  upApiUrl="uploadBase64ForApp"
                  ref="filePicUpload"
                  @on-list-change="changeUpload"
                >
                </m-upload>
              </view>
            </u-form-item>
          </u-form>
          <!-- 数据字典 -->
          <dic-choice :keyWord="dicKeyWords" :currentSelect="dicCurrentSelect" v-model="dicShow" @confirm="selectDicConfirm"></dic-choice>
        </view>
      </view>
      <view class="space-content"></view>
      <view class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="primary" v-if="typeInfo.type != 'view'" @click="saveDensBtn">
          保存
        </u-button>
      </view>
      <u-popup mode="bottom" height="80%" v-model="nativeNameSelectShow">
        <area-select @choose="nativeNameSelectShowComfir"></area-select>
      </u-popup>
      <!-- 组织机构选择 -->
      <u-popup mode="bottom" height="80%" v-model="orgSelectShow">
        <org-select :cleanParentOrg="true" :isHybrid="true" limitNodeType="03" treeType="zm-comp" @choose="handlerChooseOrg"></org-select>
      </u-popup>
    </view>
  </view>
</template>

<script>
import areaSelect from "@/components/area-select.vue";
import DensInfo from "@/declare/case/DensInfo.js";
import caseService from "@/service/case/case.service.js";
import DicChoice from "@/components/dic_choice.vue";
import DicInput from "@/components/dic_input.vue";
import OrgSelect from "@/components/org-select.vue";
import commonService from "@/service/common/common.service";
import AutoInput from "@/components/autoInput.vue";
import mUpload from '@/components/m-upload.vue';
import FormSection from "@/components/form-section.vue";
export default {
  components: {
    DicChoice,
    DicInput,
    OrgSelect,
    areaSelect,
    AutoInput,
    mUpload,
    FormSection,
  },
  data() {
    return {
      dicShow: false, // dic_select 是否显示
      dicKeyWords: "", // dic 关键字
      dicCurrentSelect: "", // dic 当前选择项
      dataForm: DensInfo.createNew(),
      orgSelectShow: false,
      nativeNameSelectShow: false,
      rules: {
        densType: [
          {
            required: true,
            message: "请选择窝点类型",
            trigger: "change",
          },
        ],
        // 名称
        densName: [
          {
            required: true,
            message: "请输入名称",
            trigger: ["change", "blur",],
          },
        ],
        densSubType:[
          {
            required: true,
            message: "请选择窝点小类",
            trigger: ["change", "blur",],
          },
        ],
        remoteOrgName:[
          {
            required: true,
            message: "请选择登记单位",
            trigger: ["change", "blur",],
          },
        ],
        denProvCityCounty:[
          {
            required: true,
            message: "请选择所在地",
            trigger: ["change", "blur",],
          },
        ],
      },
      errorType: ['border-bottom','message',],
      isTrue: true,
      isDisabled: false, // 表单是否禁用
      border: false,
      typeInfo: {}, // 类型 添加/编辑
      subTypeList:[], // 窝点小类
      subTypeShow:false,
      fileList: [],
      picIds: '20',
      densTypeShow:false,
      densTypeList:[], // 窝点类型
      prevParam:{},
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-26 fsx start
			pointerStyle: {
			  marginRight: "5px",
				pointerEvents: "none !important"
			},
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-26 fsx end
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  // 加载初始周期方法
  onLoad() {
    this.prevParam = this.getRouteParam();
    this.dataForm.caseUuid = this.prevParam.caseUuid;
    if (this.prevParam.type) {
      this.typeInfo.type = this.prevParam.type;
      this.typeInfo.typeName = this.prevParam.type === "add" ? "添加窝点" : this.prevParam.type === "edit" ? "编辑窝点" : "查看窝点";
      // 查看详情表单禁用
      if (this.prevParam.type === "view") {
        this.isDisabled = true;
      }
    } else {
      this.typeInfo = {};
    }
    // 表单处理
    if (this.prevParam.param) {
      this.refreshDens(this.prevParam.param);
    }
  },
  methods: {
    refreshDens(data){
      this.objMerge(this.dataForm, data);
      this.$set(this.dataForm, "gis", this.dataForm.gisX ? `${this.dataForm.gisX},${this.dataForm.gisY}` : "");
      this.dataForm.denProvCityCounty = this.getPlaceName(this.dataForm.provCode,this.dataForm.cityCode,this.dataForm.countyCode);
      // 获取窝点小类数据
      this.getSubType();
      if (this.dataForm.photo) {
        let photoArr = this.dataForm.photo.split(',');
        photoArr.forEach((val) => {
          this.fileList.push({
            gfiId: val,
          });
        });
      }
    },
    // 获取班次接口
    shipInfo(txt) {
      let self = this;
      let params = {
        page: 1,
        limit: 10,
        name: txt,
      }
      return new Promise((resolve, reject) => {
        if (self.$u.test.isEmpty(txt)) {
          resolve([]);
          return;
        }
        caseService.getCaseDensInfoList(params).then(res => {
          res.data.forEach(itm => {
            itm.name = itm.remoteOrgName ? [itm.densName,].join("") + '-' + itm.remoteOrgName : [itm.densName,].join("");
          });
          resolve(res.data);
        }).catch(er => {
          resolve([]);
        });
      });
    },
    // 登记单位回调事件
    handlerChooseOrg(orgs) {
      this.dataForm.remoteOrgUuid = orgs[0].id;
      this.dataForm.remoteOrgName = orgs[0].name;
      this.orgSelectShow = false;
    },
    // 行政区划确认事件
    nativeNameSelectShowComfir(areas) {
      if(this.$modal.isMuniCity(areas[0].proCode)){
        this.dataForm.denProvCityCounty = [areas[0].admdivName, areas[0].countryName,].join("");
      }else{
        this.dataForm.denProvCityCounty = [areas[0].proName, areas[0].admdivName, areas[0].countryName,].join("");
      }
      this.dataForm.provCode = areas[0].proCode;
      this.dataForm.cityCode = areas[0].admdivCode;
      this.dataForm.countyCode = areas[0].countryCode;
      this.nativeNameSelectShow = false;
    },
    // 获取行政区划名称
    getPlaceName(placeProvCode,placeCityCode,placeCountyCode){
      let areaCoinNames = '';
      if(!this.$u.test.isEmpty(placeProvCode) && !this.$modal.isMuniCity(placeProvCode)){
        areaCoinNames = commonService.getPersonLocal(placeProvCode, true).areaName || "";
      }
      if(!this.$u.test.isEmpty(placeCityCode)){
        areaCoinNames += commonService.getPersonLocal(placeCityCode, true).areaName || "";
      }
      if(!this.$u.test.isEmpty(placeCountyCode)){
        areaCoinNames += commonService.getPersonLocal(placeCountyCode, true).areaName || "";
      }
      return areaCoinNames;
    },
    // 数据字典组件选择事件
    dicSelectOpen: function(keyWords) {
      if (this.dicKeyWords == keyWords && this.dicShow) {
        return true;
      }
      return false;
    },
    showDic: function(key, cur) {
      if (this.dicShow) return;
      if (this.isDisabled) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.dicShow = true;
    },
    selectDicConfirm(e) {
      if (this.dicKeyWords == this.$u.dic.DIC_KEYS.C_DENS_TYPE) { // 窝点类型
        this.dataForm.densTypeName = e[0].label;
        this.dataForm.densType = e[0].extra.bcbCode;
        // 获取窝点小类数据
        this.getSubType();
        // 清空窝点小类数据
        this.dataForm.densSubTypeName = '';
        this.dataForm.densSubType = '';
      }
    },
    // 获取窝点小类
    getSubType(value){
      this.subTypeList = [];
      caseService.getEvidenceOptions({},'C_DENS_SUBTYPE','ext1',this.dataForm.densType).then(res => {
        this.subTypeList = res.data;
        if(this.dataForm.densSubType){
          let list = this.subTypeList.filter((item) => {
            return item.value == this.dataForm.densSubType;
          });
          this.dataForm.densSubTypeName = list[0].text;
        }

      });
    },
    // 窝点小类选择事件
    selectConfirm(e,type) {
      let name = `${type}Name`;
      let extValue = '';
      e.map((val, index) => {
        extValue = val.value;
        this.dataForm[name] = val.label;
        this.dataForm[type] = val.value;
      });
    },
    // 窝点小类
    openSubType() {
      if (this.isDisabled) return;
      this.subTypeShow = true;
    },
    // 登记单位
    openOrgSelectShow() {
      if (this.isDisabled) return;
      this.orgSelectShow = true
    },
    // 所在地
    openNativeNameSelectShow() {
      if (this.isDisabled) return;
      this.nativeNameSelectShow = true;
    },
    // 获取自定选择的数据（窝点名称）
    choiceAutoItem(itm, index){
      if(index == '1'){
        this.dataForm.caseUuid = this.prevParam.caseUuid;
        this.refreshDens({... itm,});
      }
    },
    // 保存
    saveDensBtn() {
      let self = this;
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          let { toJsonStr, updateContent, updateTime, ...params } = self.dataForm;
          let ids = [];
          if(this.fileList.length > 0){
            this.fileList.forEach((item) => {
              ids.push(item.gfiId);
            });
            params.photo = ids.join(',');
          }
          caseService
            .saveDens(params)
            .then((res) => {
              if (res.success) {
                this.$u.toast(res.msg);
                self.backPrev({
                  paramKey: "caseInfo",
                  param: {
                    isClickDensSaveBtn: true,
                    type: "dens",
                  },
                });
              } else {
                this.$u.toast("保存失败");
              }
            })
            .catch((err) => {
              this.$u.toast(err);
            });
        } else {
          console.log("表单验证失败");
        }
      });
    },
    // 经纬度
    setLocation() {
      // this.$u.route('pages/commonPage/modifyLocationMap');
      if (this.isDisabled) return;
      let self = this;
      // #ifdef H5-DINGDING
      this.$deviceApi
        .getLocationByMap(this.dataForm.gisY, this.dataForm.gisX)
        .then((latlng) => {
          self.$set(self.dataForm, "gis", `${latlng[1]},${latlng[0]}`);
          self.$set(self.dataForm, "gisX",latlng[1]);
          self.$set(self.dataForm, "gisY", latlng[0]);
        })
        .catch((err) => {
          self.$api.toast("获取位置信息失败");
        });
      // #endif

      // #ifndef H5-DINGDING
      this.$u.route("pages/commonPage/modifyLocationMap");
      // #endif
    },
    // 数据返回操作
    updateBackState(obj) {
      let self = this;
      // 经纬度
      if (obj.pos) {
        self.$set(self.dataForm, "gis", `${obj.pos.longitude},${obj.pos.latitude}`);
        self.$set(self.dataForm, "gisX", obj.pos.longitude);
        self.$set(self.dataForm, "gisY", obj.pos.latitude);
      }
    },
    // 上传/删除图片事件
    changeUpload(list, key) {
      if (list.length > 0) {
        this.fileList = [...list,];
      } else {
        this.fileList = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../case_common.scss";
.page{padding:0;}
.content {
  .party-info-content {
    padding: 10px 16px 16px;
    .party-info-title {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .p-title-text {
        font-size: $font_size_1;
        font-weight: bold;
      }
    }
  }
}
.party-info-box {
  .text-right {
    text-align: right !important;
  }
}
</style>
